package com.tma.mobilechart.line;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import javax.microedition.khronos.opengles.GL10;

import android.opengl.GLES10;
import android.util.Log;

public class Line2D {

	private FloatBuffer vertexBuffer;	// buffer holding the vertices
	private FloatBuffer colorBuffer;	// buffer holding the color
	private ByteBuffer indexBuffer;		// buffer holding the index
	
	private float yData[];
	
	private int countData = 0;
	
	private float vertices[] ;
	
	private int mColor;
	private float mRed, mBlue, mGreen;
	
	//private LineInputData mInputData;
	
	//private LineItem mItem;
	
	

	public Line2D(LineInputData mInputData, int index, int mColor) {
		
		//init data
		//this.mInputData = mInputData;
		//this.mItem = mItem;
		this.mColor = mColor;
		yData =  mInputData.getlData().get(index).getlYValue();
		countData = yData.length;
		
		vertices = getVertices2D(yData, countData, mInputData.getMaxValueY(), mInputData.getMAX_VALUE_Y(), mInputData.getMAX_VALUE_X());
		
		this.getColor(mColor);
				
		
		// a float has 4 bytes so we allocate for each coordinate 4 bytes
		ByteBuffer vertexByteBuffer = ByteBuffer.allocateDirect(vertices.length * 4);
		vertexByteBuffer.order(ByteOrder.nativeOrder());
		vertexBuffer = vertexByteBuffer.asFloatBuffer();
		vertexBuffer.put(vertices);
		vertexBuffer.position(0);
	}
	
	public void draw(GL10 gl) {
		
		//Set the face rotation
		gl.glFrontFace(GL10.GL_CW);
		
		// Point to our vertex buffer
		gl.glVertexPointer(3, GLES10.GL_FLOAT, 0, vertexBuffer);		
		
		//Enable the vertex and color state
		gl.glEnableClientState(GLES10.GL_VERTEX_ARRAY);
		
		// set the colour 
		gl.glColor4f(mRed, mGreen, mBlue, 1.0f);		

		// Draw the vertices
		gl.glDrawArrays(GLES10.GL_LINE_STRIP, 0, vertices.length / 3);

		//Disable the client state before leaving
		gl.glDisableClientState(GLES10.GL_VERTEX_ARRAY);
	}
		
	
	public float[] getVertices2D(float[] array, int sizeData, float maxData, float MAX_VALUE_Y, float MAX_VALUE_X)
	{
		float[] result, y, x;
		y = new float[sizeData];
		x = new float[sizeData];
		result = new float[sizeData*3];
		for(int i = 0; i < sizeData; i++)
		{
			y[i] = array[i] / maxData * MAX_VALUE_Y - 0.5f;			
			x[i] = (float) i / sizeData * MAX_VALUE_X - 0.5f;
			result[i*3] = x[i];
			result[i*3+1] = y[i];
			result[i*3+2] = -0.25f;
		}
		return result;
	}
	
	public void getColor(int color)
	{
		mRed = (color & 0x00ff0000) >> 16;
		mGreen = (color & 0x0000ff00) >> 8;
		mBlue = (color & 0x000000ff);
	}
		
}